<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true" label-width="100px">
      <el-form-item label="工号" prop="staffNo">
        <el-input v-model="queryParams.staffNo" placehodler="请输入工号"
                  clearable size="small" @keyup.enter.native="handleQuery"
        ></el-input>
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="queryParams.name" placehodler="请输入姓名"
                  clearable size="small" @keyup.enter.native="handleQuery"
        ></el-input>
      </el-form-item>
      <el-form-item label="题库名称" prop="questionBankName">
        <el-select v-model="queryParams.questionBankName" placeholder="请输入题库名称" clearable size="small">
          <el-option v-for="(p,index) in questionBankListOptions"
                     :key="index"
                     :label="p.questionBankName"
                     :value="p.questionBankName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="考试状态" prop="examStatus">
        <el-select v-model="queryParams.examStatus" placeholder="请选择考试状态" clearable size="small">
          <el-option v-for="dict in examStatusOptions"
                     :key="dict.code"
                     :label="dict.name"
                     :value="dict.code"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="取证状态" prop="obtainEvidenceStatus">
        <el-select v-model="queryParams.obtainEvidenceStatus" placeholder="请选择取证状态" clearable size="small">
          <el-option v-for="dict in obtainEvidenceStatusOptions"
                     :key="dict.code"
                     :label="dict.name"
                     :value="dict.code"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item style="margin-left: 10px">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button style="margin-left: 10px" icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini"
                   @click="handleAdd"
        >报名
        </el-button>
        <el-button type="primary" icon="el-icon-edit-outline" size="mini" :disabled="multiple"
                   @click="handleErrorExam"
        >继续考试
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple"
                   @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" icon="el-icon-upload2" size="mini"
                   @click="handleImport"
        >导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-download" size="mini"
                   @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table :data="signUpList" v-loading="loading"  @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" align="center" width="50" type="index"/>
      <el-table-column label="工号" align="center" prop="staffNo" :show-overflow-tooltip="true"/>
      <el-table-column label="姓名" align="center" prop="name" :show-overflow-tooltip="true"/>
      <el-table-column label="部门" align="center" prop="userDeptName" :show-overflow-tooltip="true"/>
      <el-table-column label="项目代码" align="center" prop="projectCode" :show-overflow-tooltip="true"/>
      <!--            <el-table-column label="项目名称" align="center" prop="projectName" :show-overflow-tooltip="true"/>-->
      <el-table-column label="题库" align="center" prop="questionBankName" :show-overflow-tooltip="true"/>
      <el-table-column label="考场" align="center" prop="examPlanDTO.examRoomId" :formatter="examRoomFormat"
                       :show-overflow-tooltip="true"/>
      <el-table-column label="考试时间" align="center" width="180" :show-overflow-tooltip="true">
        <template slot-scope="scope" v-if="scope.row.examPlanDTO.examDate !== null ? true : false">
          <span>{{ scope.row.examPlanDTO.examDate }}&nbsp;{{ scope.row.examPlanDTO.examStart }}~{{ scope.row.examPlanDTO.examEnd }}</span>
        </template>
      </el-table-column>
      <el-table-column label="考试状态" align="center" prop="examStatus" :formatter="examStatusFormat"
                       :show-overflow-tooltip="true"
      ></el-table-column>
      <el-table-column label="报名状态" align="center" prop="signUpStatus" :formatter="signUpStatusFormat"
                       :show-overflow-tooltip="true"
      ></el-table-column>
      <el-table-column label="取证状态" align="center" prop="obtainEvidenceStatus" :formatter="obtainEvidenceStatusFormat"
                       :show-overflow-tooltip="true"
      ></el-table-column>
      <el-table-column label="是否补考" align="center" prop="isSignUp" :formatter="isSignUpStatusFormat"
                       :show-overflow-tooltip="true"
      ></el-table-column>
      <el-table-column label="身份证号" align="center" prop="IDCard" :show-overflow-tooltip="true"/>
      <el-table-column label="上机等级" align="center" prop="levelOfOperation" :show-overflow-tooltip="true"/>
      <el-table-column label="专业组" align="center" prop="professionalGroup":show-overflow-tooltip="true"/>
      <el-table-column label="操作" align="center" width="260">
        <template slot-scope="scope">
          <el-button type="text" size="mini" icon="el-icon-view" @click="review(scope.row)"
          >详情
          </el-button>
          <el-button
                  v-if="scope.row.signUpStatus!='0' && scope.row.signUpStatus!='1' && scope.row.examPlanDTO.examRoomId === null"
                  type="text" size="mini" icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
                  v-if="scope.row.signUpStatus!='0' && scope.row.signUpStatus!='1' && scope.row.examPlanDTO.examRoomId !== null"
                  type="text" size="mini" icon="el-icon-edit"
                  @click="postponeExam(scope.row)"
          >延期
          </el-button>
          <el-button v-if="scope.row.signUpStatus!='0' && scope.row.examPlanDTO.examRoomId !== null" type="text"
                     size="mini" icon="el-icon-edit"
                     @click="cancelExam(scope.row)"
          >取消
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
            v-show="total>0"
            :total="total"
            :page.sync="pageParams.page"
            :limit.sync="pageParams.rows"
            @pagination="getList"
    />

    <!-- 报名导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
              ref="upload"
              :limit="1"
              accept=".xlsx, .xls"
              :headers="upload.headers"
              :action="upload.url + '?uploadType=' + this.uploadType"
              :disabled="upload.isUploading"
              :on-progress="handleFileUploadProgress"
              :on-success="handleFileSuccess"
              :auto-upload="false"
              drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <div>
            <div style="margin-bottom: 10px">
              请选择上传类型：
            </div>
            <el-radio-group v-model="uploadType" style="margin-bottom: 10px">
              <el-radio :label="'0'">通用</el-radio>
              <el-radio :label="'1'">技能鉴定</el-radio>
            </el-radio-group>
          </div>
          <div>
            <div style="margin-bottom: 10px">
              请选择下载模板类型：
            </div>
            <el-radio-group v-model="questionBankType" style="margin-bottom: 10px">
              <el-radio :label="'0'">通用</el-radio>
              <el-radio :label="'1'">技能鉴定</el-radio>
            </el-radio-group>
            <div>
              <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
            </div>
          </div>
        </div>
        <div class="el-upload__tip" style="color:#ff0000" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="submitFileForm">确 定</el-button>
        <el-button size="mini" @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 新增修改 -->
    <el-dialog v-if="signUpOpen" :title="title" :visible.sync="signUpOpen" width="660px" append-to-body>
      <sign-up ref="signUp" @submitForm="getList" @cancelDialog="cancelDialog"></sign-up>
    </el-dialog>
    <!-- 取消或延期编辑 -->
    <el-dialog v-if="cancelOrPostponeOpen" :title="title" :visible.sync="cancelOrPostponeOpen" width="660px"
               append-to-body>
      <cancelOrPostpone ref="cancelOrPostpone" @submitSuccess="submitSuccess" @cancelDialog="cancelDialog"></cancelOrPostpone>
    </el-dialog>
    <!-- 详情区域 -->
    <el-dialog v-if="openReview" :title="'详情'" :visible.sync="openReview" width="660px"
               append-to-body>
      <review ref="review" :form="form" :cancelOpen="cancelOpen" :postponeOpen="postponeOpen" @submitForm="getList"
              @cancelDialog="cancelDialog"></review>
    </el-dialog>
    <!-- 导出弹出框 -->
    <el-dialog v-if="openExport" title="导出类型选择" :visible.sync="openExport" width="260px">
      <div>
        <el-row :gutter="10">
          <el-col :span="24" style="margin-bottom: 20px">
            请选择导出类型：
          </el-col>
          <el-col :span="24">
            <el-radio-group v-model="questionBankType">
              <el-radio :label="'0'">通用</el-radio>
              <el-radio :label="'1'">技能鉴定</el-radio>
            </el-radio-group>
          </el-col>
          <el-col :span="24" align="center" style="margin-top: 20px">
            <el-button size="mini" type="primary" @click="executeExport">确 定</el-button>
            <el-button size="mini" @click="cancelExport">取 消</el-button>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {listQuestionBank} from "@/api/question/questionBank"
  import {deleteSignUp, exportSignUp, getSignUpList, getSignUpListById,goOnExam,importTemplate} from "@/api/exam/signUp"
  import signUp from "./form/signUp"
  import cancelOrPostpone from "./form/cancelOrPostpone"
  import review from "./form/review"
  import {getToken} from "@/utils/auth";
  import {getExamRoomList} from "@/api/exam/examRoom";
  export default {
    name: "index",
    components: {
      signUp, cancelOrPostpone, review
    },
    data() {
      return {
        // 遮罩层
        loading: false,
        //总条数
        total: 0,
        //显示搜索条件
        showSearch: true,
        // 已安排考试计划的记录
        records: [],
        //选中工号数组
        staffNos: [],
        //选中报名信息id数组
        signUpIds: [],
        // 选中报名信息
        signUpIdInfos: [],
        //非多个禁用
        multiple: true,
        //详情开关
        openReview: false,
        // 分页参数
        pageParams: {
          page: 1,
          rows: 10,
        },
        //表单数据
        queryParams: {},
        //题库列表项
        questionBankListOptions: [],
        // 考试状态字典
        examStatusOptions: [],
        // 报名状态字典
        signUpStatusOptions: [],
        // 取证状态字典
        obtainEvidenceStatusOptions: [],
        // 是否补考状态字典
        isSignUpStatusOptions: [],
        // 题库类型 0：通用，1：技能鉴定，2：工艺
        questionBankType: '0',
        // 上传类型 0：通用，1：技能鉴定
        uploadType: '0',
        // 导出弹框开关
        openExport: false,
        //报名表
        signUpList: [],
        // 考场列表数据
        examRoomList: [],
        // 报名详情表单
        form: {},
        //取消原因详情开关
        cancelOpen: false,
        //延期原因详情开关
        postponeOpen: false,
        //报名编辑开关
        signUpOpen: false,
        //取消或延期编辑开关
        cancelOrPostponeOpen: false,
        //dialog标题
        title: "",
        // 报名导入参数
        upload: {
          // 是否显示弹出层（导入）
          open: false,
          // 弹出层标题（导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 设置上传的请求头部
          headers: {
            "token": getToken(),
            Authorization: 'Basic YXZpY2l0MjAxNTphdmljaXQyMDE1',
            "X-Access-Token": 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJBcHDliY3nq6_mjojmnYMiLCJhdWQiOiIxIiwiQVBQX0lEIjoiMSIsIkxBTkdVQUdFX0NPREUiOiJ6aF9DTiIsIm5iZiI6MTU5NDEwOTI4NSwiaXNzIjoiQVZJQy1ESUdJVEFMIiwiZXhwIjozMTcxOTQ2MDk1LCJPUkdfSURFTlRJVFkiOiJPUkdfUk9PVCIsIlVTRVJfREVQVF9JRCI6IjEiLCJpYXQiOjE1OTQxMDkyODUsImp0aSI6IjY1MGFlNDU1LWE0OWEtNGVkYi1hODhlLThhODAwZGRmNmMwZiJ9.cL7yCcN04i3pCGCTsZ9gZMAhrX21kjQbAlX34RzPMXg'
          },
          // 上传的地址
          url: process.env.VUE_APP_EXAM_API + "api/uf/boostor/exam/signUp/ExamSignUpRest/importData/v1"
        },
      }
    },
    //初始化数据
    created() {
      //题库信息
      listQuestionBank({
        'pageParameter': {"page": 1, "rows": 1000},
        'searchParams': {}
      }).then(response => {
        this.questionBankListOptions = response.responseBody.result;
      })
      //考试状态
      this.getDicts("exam_status").then(response => {
        this.examStatusOptions = response.responseBody.result;
      });
      //报名状态
      this.getDicts("exam_sign_up_status").then(response => {
        this.signUpStatusOptions = response.responseBody.result;
      });
      //取证状态
      this.getDicts("exam_obtain_evidence_status").then(response => {
        this.obtainEvidenceStatusOptions = response.responseBody.result;
      });
      //是否补考状态
      this.getDicts("exam_is_sign_up").then(response => {
        this.isSignUpStatusOptions = response.responseBody.result;
      });
      //报名表
      this.getList();
      // 初始化考场列表
      this.getRoomList();

    },
    methods: {
      //查询报名列表
      getList() {
        this.loading = true;
        getSignUpList({
          'pageParameter': this.pageParams,
          'searchParams': this.queryParams
        }).then(response => {
              this.signUpList = response.responseBody.result;
              this.total = response.responseBody.pageParameter.totalCount;
            }
        )
        this.loading = false;
      },
      //查询考场信息
      getRoomList() {
        getExamRoomList({
          'pageParameter': {"page": 1, "rows": 1000},
          'searchParams': {}
        }).then(response => {
          this.examRoomList = response.responseBody.result;
        })
      },
      // 考场翻译
      examRoomFormat(row, column) {
        const examRoomId = row.examPlanDTO.examRoomId;
        // console.log("= 考场Id ==",examRoomId);
        // 考场列表
        const datas = this.examRoomList;
        var actions = [];
        Object.keys(datas).some((key) => {
          if (datas[key].examRoomId == (examRoomId)) {
            actions.push(datas[key].examRoomName);
            return true;
          }
        })
        return actions.join('');
      },
      //新增
      handleAdd() {
        this.title = "添加报名信息";
        this.signUpOpen = true;
      },
      // 继续考试
      handleErrorExam() {
        const signUpIdInfos = this.signUpIdInfos;
        console.log("继续考试信息：",signUpIdInfos)
        for (let i = 0; i < signUpIdInfos.length; i++) {
          var signUpIdInfo = signUpIdInfos[i];
          if (signUpIdInfo.examStatus !== '3') { // 不属于异常考试
            this.msgWarning(signUpIdInfo.name+"参加的项目："+signUpIdInfo.projectName+"，属于非考试异常，请重新选择！");
            return;
          }
        }
        this.$confirm("确定"+signUpIdInfo.name+"参加的项目："+signUpIdInfo.projectName+"继续考试！", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          goOnExam(signUpIdInfos).then(res => {
            if (res.responseBody > 0) {
              this.msgSuccess(res.message);
              //刷新报名列表
              this.getList();
            } else {
              this.msgWarning(res.message);
            }
          }).catch(err => {});
        }).catch(() => {});
      },
      //修改
      handleUpdate(row) {
        this.title = "修改报名信息";
        this.signUpOpen = true;
        this.$nextTick(() => {
          getSignUpListById(row.signUpId).then(response => {
            // 如果报名类型为技能鉴定，需要打开技能鉴定区域
            if(response.responseBody.questionBankType === '1'){
              this.$refs.signUp.openSkillAppraisal = true
            }
            this.$refs.signUp.form = response.responseBody;
          })
        })
      },
      //删除
      handleDelete(row) {
        // 已安排考试计划的记录不允许删除
        if(this.records && this.records.length > 0){
          this.$message.error('工号为：' + this.records + '的数据项已安排考试计划，不允许删除')
          return
        }
        const staffNos = row.staffNo || this.staffNos
        const signUpIds = row.signUpId || this.signUpIds;
        this.$confirm("确认删除工号为：（" + staffNos + "）的数据项", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.loading = true;
          deleteSignUp(signUpIds).then(response => {
            this.getList();
            this.msgSuccess("删除成功");
          })
        }).catch(() => {
        }).finally(() => {
          this.loading = false;
        });
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.records = []
        selection.forEach(item => {
          // 保存已安排考试计划的记录
          if(item.examPlanId){
            this.records.push(item.staffNo)
          }
        })
        this.staffNos = selection.map(item => item.staffNo)
        this.signUpIds = selection.map(item => item.signUpId)
        this.signUpIdInfos = selection.map(item => item)
        this.multiple = !selection.length
      },
      //取消考试
      cancelExam(row) {
        this.title = "取消考试";
        this.cancelOrPostponeOpen = true;
        this.$nextTick(() => {
          getSignUpListById(row.signUpId).then(response => {
            this.$refs.cancelOrPostpone.form = response.responseBody;
            this.$refs.cancelOrPostpone.form.signUpStatus = "0";
            this.$refs.cancelOrPostpone.cancelOpen = true;
            this.$refs.cancelOrPostpone.postponeOpen = false;
          })
        })
      },
      //延期考试
      postponeExam(row) {
        this.title = "延期考试";
        this.cancelOrPostponeOpen = true;
        this.$nextTick(() => {
          getSignUpListById(row.signUpId).then(response => {
            this.$refs.cancelOrPostpone.form = response.responseBody;
            this.$refs.cancelOrPostpone.form.signUpStatus = "1";
            this.$refs.cancelOrPostpone.cancelOpen = false;
            this.$refs.cancelOrPostpone.postponeOpen = true;
          })
        })
      },
      //详情
      review(row) {
        getSignUpListById(row.signUpId).then(response => {
          this.form = response.responseBody;
          this.cancelOpen = response.responseBody.signUpStatus === '0' ? true : false;
          this.postponeOpen = response.responseBody.signUpStatus === '1' ? true : false;
          this.openReview = true;
        })
      },

      // 提交成功回调
      submitSuccess(){
        this.cancelDialog()
        this.getList()
      },

      // 取消回调
      cancelDialog() {
        this.signUpOpen = false;
        this.cancelOrPostponeOpen = false;
        this.openReview = false;
      },
      //重置
      resetQuery() {
        this.queryParams = {}
        this.handleQuery();
      },
      //查询
      handleQuery() {
        this.getList();
      },
      //考试状态字典回显
      examStatusFormat(row, col) {
        return this.selectDictLabel(this.examStatusOptions, row.examStatus);
      },
      //报名状态字典回显
      signUpStatusFormat(row, col) {
        return this.selectDictLabel(this.signUpStatusOptions, row.signUpStatus);
      },
      //取证状态字典回显
      obtainEvidenceStatusFormat(row, col) {
        return this.selectDictLabel(this.obtainEvidenceStatusOptions, row.obtainEvidenceStatus);
      },
      //是否补考状态字典回显
      isSignUpStatusFormat(row, col) {
        return this.selectDictLabel(this.isSignUpStatusOptions, row.isSignUp);
      },

      /** 导出按钮操作 */
      handleExport() {
        this.questionBankType = '0'
        this.openExport = true
      },

      // 导出
      executeExport(){
        this.$confirm('确认导出所有报名数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.openExport = false
          this.queryParams.questionBankType = this.questionBankType
          exportSignUp({searchParams: this.queryParams}).then(response => {
            this.download(response.responseBody);
          })
        }).catch(() => {})
      },

      // 取消
      cancelExport() {
        this.openExport = false
      },

      /** 导入按钮操作 */
      handleImport() {
        this.upload.title = "报名信息导入";
        this.questionBankType = '0'
        this.upload.open = true;
      },
      /** 下载模板操作 */
      importTemplate() {
        importTemplate(this.questionBankType).then(response => {
          this.download(response.responseBody);
        });
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        if (response.retCode === '200') {
          this.$alert(response.responseBody, "导入结果", {dangerouslyUseHTMLString: true});
          this.getList();
        } else {
          this.$alert(response.errorDesc, "导入结果", {dangerouslyUseHTMLString: true});
        }
      },
      // 提交上传文件
      submitFileForm() {
        const uploadTypeStr = this.uploadType === '0' ? '通用' : '技能鉴定'
        this.$confirm('当前选择的上传类型为\"' + uploadTypeStr + '\",确定上传吗？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$refs.upload.submit();
        })
      }
    }
  }
</script>
